package com.elvin.zoe.parser.jiayuan;

import java.util.ArrayList;
import java.util.List;

import com.elvin.zoe.parser.AbstractParser;
import com.elvin.zoe.pojo.JiayuanMessage;
import com.elvin.zoe.pojo.Message;

public class JiayuanParser extends AbstractParser {

	@Override
	protected List<String> getMessageTokens(String originalHtml) {
        String messageStartToken = "<div class=\"con\">";
        String messageEndToken = "</div>";
        List<String> messageTokens = new ArrayList<String>();
        int tokenStart = originalHtml.indexOf(messageStartToken);
        while (tokenStart > 0) {
            int tokenEnd = originalHtml.indexOf(messageEndToken, tokenStart) + messageEndToken.length();
            messageTokens.add(originalHtml.substring(tokenStart, tokenEnd));
            tokenStart = originalHtml.indexOf(messageStartToken, tokenEnd);
        }
        return messageTokens;
	}

    @Override
    protected int getMessageType(String messageToken) {
        if(messageToken.indexOf("<b class=\"ly1\">") > 0)
            return Message.INCOMMING;
        else
            return Message.OUTGOING;
    }

    @Override
    protected String getMessageDatetime(String messageToken) {
        String startToken = "<span>";
        int tokenStart = messageToken.indexOf(startToken) + startToken.length();
        int tokenEnd = messageToken.indexOf("</span>", tokenStart);
        String datetimeToken = messageToken.substring(tokenStart, tokenEnd);
        return datetimeToken;
    }

	@Override
	protected String getMessageDatetimeFormat() {
		return "yy-MM-dd HH:mm";
	}

	@Override
	protected List<Message> parseMessagesFromTokens(List<String> messageTokens) throws Exception {
        List<Message> messages = new ArrayList<Message>();
        for (String messageToken : messageTokens) {
            int type = getMessageType(messageToken);
            String datetimeFormat = getMessageDatetimeFormat();
            String datetime = getMessageDatetime(messageToken);
            String text = getMessageText(messageToken);
            messages.add(new JiayuanMessage(type, datetime, datetimeFormat, text));
        }
        return messages;
	}

	private String getMessageText(String messageToken) {
        String refined = messageToken.replaceAll("&nbsp;", "");
        String textStartToken = "<dd class=\"c\">";
        int tokenStart = refined.lastIndexOf(textStartToken) + textStartToken.length();
        int tokenEnd = refined.indexOf("</dd>", tokenStart);
        return refined.substring(tokenStart, tokenEnd);
	}


}
